/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.supinfo.youfood.web.servlet;

import com.supinfo.youfood.entity.Employe;
import com.supinfo.youfood.service.EmployeService;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Michael
 */
@WebServlet(name = "LoginServlet", urlPatterns = {"/Login"})
public class LoginServlet extends HttpServlet {
    
    /**
     * Attributs
     */
    @EJB
    private EmployeService employeservice;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        boolean succes = false;
        int code_acces = Integer.parseInt(request.getParameter("code_acces"));
        
        HttpSession session = request.getSession(true);
        
        Employe e = new Employe(code_acces);
        
        if(employeservice.login(e) != null) {
            Employe currentEmp = employeservice.login(e);
            
            //Employe courant mis en session
            session.setAttribute("currentEmp", currentEmp);
            
            //On redirige selon le type de personne qui se connecte
            if(currentEmp.getType_employe().getDroits() > 600) {
                succes = true;
                request.setAttribute("succes", succes);
                response.sendRedirect("/YouFood/admin/accueil");
            }    
            else if(currentEmp.getType_employe().getDroits() == 111) {
                succes = true;
                request.setAttribute("succes", succes);
                request.getRequestDispatcher("/jsp/client/pre-accueil.jsp").forward(request, response);
            }
            else if(currentEmp.getType_employe().getDroits() == 555) {
                succes = true;
                request.setAttribute("succes", succes);
                response.sendRedirect("/YouFood/cuisine");
            }
            else if(currentEmp.getType_employe().getDroits() == 222) {
                succes = true;
                request.setAttribute("succes", succes);
                response.sendRedirect("serveur/accueil");
            }
        }
        else {
            request.setAttribute("succes", succes);
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }
    }
}
